<div id="wrapMain">
            <div class="wrap_1024" style="margin-bottom:40px">

            <div class='head_nav'><span class="icon-picture"></span> Get story</div>
            <div class="user_profile">
				
				<div class="row" >
					<div class="col-md-12 ">
						<div id="contentIndex" class="col-md-12">
		 							Tổng cộng: <?php echo $data['total_truyen']; ?> truyện.<br />
                                    Lấy: <?php echo $data['limit_stories']; ?> truyện <br />
										<div role="dialog" id="modalAlertBox" class="modal fade" style="display: none;">
											<div class="modal-dialog modal-wide">
												<div class="modal-content">
													<div class="modal-header">
														<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
														<h4 class="modal-title"></h4>
													</div>
											        <div class="modal-body">
														
														<div style="clear:both"></div>
											        </div>
												</div><!-- /.modal-content -->
											</div>
										</div>
										
										<div id="wrapLoadMoreItems">
											<div class="normalLoadBtn" id="loadMoreItems"><img width="20" alt="loading" src="public/images/loading.gif"> Loading </div><br>
										</div>
										<div class="formLoading"></div>
										
									    <div class="generalError" style="display: none;"></div>
									    <form id="videoUpload" class="userPostForm" role="form" method="post" enctype="multipart/form-data">
											
											
											<div id="list_story" style="height: 300px; overflow: scroll;">
												<?php
												if($data['stories']):
												
												?>
												<table class="story_table" id="report_chapter_table">
													<thead>
														<tr>
															<th align="center">Stt</th>
															<th align="center">Title</th>
															<th align="center">Last link</th>
															<th align="center">Page</th>
														</tr>
													</thead>
													<tbody>
													
												
												<?php 
													$i = 1;
													foreach($data['stories'] as $story):
												?>
														<tr>
															<td align="center"><?= $i ?></td>
															<td align="left"><?= $story['ten']; ?></td>
															<td align="left"><?= $story['getlink_last'] ?></td>
															<td align="center"><?= $story['getlink_page'] ?></td>
															
														</tr>
												<?php 
													$i++;
													endforeach;
													?>
													</tbody>	
												</table>
												<?php 
												endif;
												?>
												
											</div>
											
											
                                            <div class="row"> <!-- Start class row wrap upload image and submit button -->
                                            <div class="col-md-2">
                                            </div>
                                            <div class="col-md-10">
											<button type=submit class="btn btn-primary mySubmit" id="submitAuto">
							                    <i class="glyphicon glyphicon-hand-up"></i>
							                    <span>Đăng bài</span>
							                </button>
                                            </div> <!-- End of class col-md-10 wrap upload image and submit button -->
                                            </div><!-- End of class row wrap upload image and submit button -->
											
										</form>
				
						</div><!-- end #contentIndex -->
					</div>
					
					
				</div> <!-- End of row -->
				<!-- <div class="row" id="report_chapter">
				<table class="story_table" id="report_chapter_table">
					<thead>
						<tr>
							<th align="center">Stt</th>
							<th align="center">Link</th>
							<th align="center">Title</th>
							<th align="center">Page</th>
							<th align="center">Tập</th>
							<th align="center">Chương</th>
							<th align="center">Status</th>
						</tr>
					</thead>
					
					
				</table>
				</div> -->
			</div><!-- end wrap_1024 -->
		</div><!-- end wrapMain -->
		
<!-- end #wrapMain -->		
		

<script type="text/javascript">
	$(document).ready(function(){
		
		
	    $('.createAlbum').click(function(e){
		    e.preventDefault();
		    $('#txtAlbum_message').remove();
		    $('#modalAlbumBox').remove();
		    var that = this;
			$.ajax({
				url : "<?php echo BASE_URL ?>index.php?module=user&act=ajax&albumBox=1",
				success : function(data){
					$('.createAlbum').parent().append(data);
					$('.createAlbum').parent().find('#modalAlbumBox').modal();
				},
			});
		});

	    $('#txtTitle').blur(function(){
	    	$.ajax({
	    		url: "index.php?module=user&act=ajax&validateTitle=1",
	    		type: 'POST',
	    		data: {txtTitle: $('#txtTitle').val()},
	    		success: function(data){
	    			newData = $.parseJSON(data);
	    			if(newData.errors){
		    			
		    			if($('#txtTitle_error').length <= 0){
			    		
		    				$('#txtTitle').parent().append('<div id="txtTitle_error" class="alert alert-danger alert-dismissable" style="display: none;"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'+newData.errors.txtTitle+'</div>');
		    				$('#txtTitle_error').slideDown('fast');
		    			}else{
							$('#txtTitle_error').html(newData.errors.txtTitle);
		    			}
	    				
	    			}else{
	    				$('#txtTitle_error').remove();
	    			}
	    		}
	    	});
	    });

	    $('#txtDescription').blur(function(){
	    	//$(this).parent().find('.alert').remove();
	    	$.ajax({
	    		url: "index.php?module=user&act=ajax&validateDescription=1",
	    		type: 'POST',
	    		data: {txtDescription: $('#txtDescription').val()},
	    		success: function(data){
	    			newData = $.parseJSON(data);
	    			//console.log(newData);
	    			if(newData.errors.txtDescription){
	    				if($('#txtDescription_error').length <= 0){
		    				$('#txtDescription').parent().append('<div id="txtDescription_error" class="alert alert-danger alert-dismissable" style="display: none;"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'+newData.errors.txtDescription+'</div>');
		    				$('#txtDescription_error').slideDown('fast');
	    				}else{
							$('#txtDescription_error').html(newData.errors.txtDescription);
		    			}
	    			}else{
	    				$('#txtDescription_error').remove();
	    			}
	    		}
	    	});
	    });

	    /*
	     * Submit event
	     */
	    $('button#submitAuto').click(function(e){
			
	    	e.preventDefault();
	    	$(".alert").remove();
	  		$('.userPostForm').css('opacity', '0.3');
			$('.formLoading')
			.css('width', $('#videoUpload').width())
			.css('height', $('#videoUpload').height())
			.css('opacity', '1')
			.css('z-index','9999').css('display', 'block');
			$('#wrapLoadMoreItems').css('display', 'block').center();
			
	    	$.ajax({
	    		url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&getStories=1",
	    		type : 'POST',
	    		async: false,
	    		cache: false,
	    		data : {
	    			submitScan: '1',
	    		},
	    		
	    		success : function(storiesEncode){

		    		if(storiesEncode != '0'){
						stories = $.parseJSON(storiesEncode);
				
						//console.log(stories);
						/*
						* Lặp truyện có auto scan = 1
						* Ở mỗi truyện đều có trang cuối cùng đã lấy link chapter (getlink_page) và link cuôi đã lấy (getlink_last)
						*/
						$.each(stories, function(e, index){
							
							returnSend = false;
							index.startPage = index.pattern_url.replace('%s%', index.getlink_page);
							
							// Sử dụng ajax để scan link chương của mỗi truyện
							$.ajax({
								url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&autoScanLinks=1",
								type: 'POST',
								data: {dataStory: index},
								async: false,
								success: function(dataReturn){
									
									//console.log(index);
									//console.log(dataReturn);
									/*
										Giá trị trả về từ hàm scan chương (autoGetChapters)
										Nếu biến dataStory không có thì kết quả trả về từ ajax là error_story
									*/
									//console.log(dataReturn);
									
									if(dataReturn == 'error_story'){


									}else if(dataReturn == 'het'){
										returnSend = true;
									}else{
										//console.log(truyen);
										/*
										dataReturn lúc này sẽ là mảng chứa các links chapter mới (CHƯA LÀM)
										*/
									
										newDataReturn = $.parseJSON(dataReturn);

										/*
											KHÓ NHẤT
											Nếu có, phải tiếp tục qua page kế tiếp để scan, <<< dùng đệ quy hàm
											Truyền vào 2 tham số dataStory: mảng chứa thông tin truyện
											
										*/

										
										// Get content from story
										if(index.getlink_type == 3){
											index = getAutoChaptersViaPage(index, newDataReturn);
											submitStoryChapterContentViaPhantom(index.story_id);
										}else{
											index = getAutoChaptersViaPage(index, newDataReturn);
											getChaptersViaPage(index);
											submitStoryChapterContent(index.story_id);
										}
										
										
												
										
										/*$.ajax({
								    		url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&requestSubmitStoryChapters=1",
								    		type : 'POST',
								    		cache: false,
								    		async: false,
								    		data: {story_id:index.story_id},
								    		success: function(){
												console.log('done get auto');
									    	},

									    	complete: function(){
												$.ajax({
													url: "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&removeAutoScan=1",
													type : 'POST',
													cache: false,
													async: false,
													data : {story_id: index.story_id},
													success: function(){}
												});
										    }
									    	
										});*/
									}
								},
							});
						});
		    		}

		    		/*if(data) newData = $.parseJSON(data);
		    		if(newData.message){
		    			popupMessage('Thông báo', [newData.message], 'alert-info');
		    		}
		    		getChaptersViaPage(newData);*/
		    	},

	    		complete: function(){
					$('.formLoading').hide();
		    		$('#wrapLoadMoreItems').hide();
		    		$('.userPostForm').css('opacity', '1');
				}
	    	});
	    });

	    function submitStoryChapterContent(storyId){

			/*
			* Đếm số chapter chưa lấy nội dung
			* Cho mỗi lần request để insert chapter_content là 100
			* Tìm tổng số request. Vd: nếu tổng số chapter là 513 thì ceil(513/100) = 6 lần request để insert hết 513 chương
			* Nếu tổng số chapter < 100 thì chỉ request 1 lần
			*/

			// Tìm tổng số chapter của truyện chưa lấy nội dung
			$.ajax({
				url: "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&hasNotInsertChapterContent=1",
				type: 'POST',
				cache: false,
				async: false,
				data: {story_id: storyId},
				success: function(data){
					if(data == '1'){
						requestSubmitStoryChapters(storyId);
						submitStoryChapterContent(storyId);
					}else{
						$.ajax({
							url: "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&removeAutoScan=1",
							type : 'POST',
							cache: false,
							async: false,
							data : {story_id: storyId},
							success: function(){}
						});
						return;
					}
					
				}
			});
		   	
	   		
	   	}

		function requestSubmitStoryChapters(storyId){
		   	
	   		$.ajax({
	    		url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&requestSubmitStoryChapters=1",
	    		type : 'POST',
	    		cache: false,
	    		async: false,
	    		timeout: 1800000, // sets timeout to 3 seconds
	    		data: {story_id:storyId},
	    		success : function(data){
		    		console.log(data);
	    			$('#wrapLoadMoreItems').css('display', 'none');
		    		if(data){
						returnData = $.parseJSON(data);
						if(returnData.error){
							
							//popupMessage('Lỗi', [returnData.error], 'alert-danger');
							if(returnData.fail_chapters){
								$.each(returnData.fail_chapters, function(i1, index1){
									//console.log(index1);
									//$('#report_chapter_content_table tbody').append('<tr><td>'+index1.truyen_id+'</td><td>'+index1.ten_truyen+'</td><td>'+index1.truyen_chuong_link_id+'</td><td>'+index1.thutu+'</td></tr>');
								});
							}
						}
		    		}
		    		
		    	}
	    	});
		}


		function submitStoryChapterContentViaPhantom(storyId){
	   		$.ajax({
				url: "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&hasNotInsertChapterContent=1",
				type: 'POST',
				cache: false,
				async: false,
				data: {story_id: storyId},
				success: function(data){
					if(data == '1'){
						requestSubmitStoryChaptersViaPhantom(storyId);
						submitStoryChapterContentViaPhantom(storyId);
					}else{
						$.ajax({
							url: "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&removeAutoScan=1",
							type : 'POST',
							cache: false,
							async: false,
							data : {story_id: storyId},
							success: function(){}
						});
						return;
					}
					
				}
			});
	   	}

		function requestSubmitStoryChaptersViaPhantom(storyId){
	   		$.ajax({
	    		url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&requestSubmitStoryChaptersViaPhantom=1",
	    		type : 'POST',
	    		cache: false,
	    		async: false,
	    		timeout: 1800000, // sets timeout to 3 seconds
	    		data: {story_id:storyId},
	    		success : function(data){
		    		console.log(data);
	    			$('#wrapLoadMoreItems').css('display', 'none');
		    		if(data){
						returnData = $.parseJSON(data);
						if(returnData.error){
							//popupMessage('Lỗi', [returnData.error], 'alert-danger');
							if(returnData.fail_chapters){
								$.each(returnData.fail_chapters, function(i1, index1){
									//console.log(index1);
									$('#report_chapter_content_table tbody').append('<tr><td>'+index1.truyen_id+'</td><td>'+index1.ten_truyen+'</td><td>'+index1.truyen_chuong_link_id+'</td><td>'+index1.thutu+'</td></tr>');
								});
							}
						}
		    		}
		    	}
	    	});
		}

	    
	    function getAutoChaptersViaPage(story, linksReturn){
			//console.log(linksReturn);
			//console.log(story);
			linkParse = JSON.stringify(linksReturn);
			story.story_id = story.id;
			story.startPage = story.getlink_page;
			alert('here in get auto ');
			if(story.getlink_type == 3){
				ajaxSubmit = 'requestSubmitStoryChaptersViaPhantom';

			}else{
				ajaxSubmit = 'requestSubmitStoryChapters';
			}
			
		    /*
		    	Dùng regex để thay thế số page hiện tại
		    	Nếu trường hợp linksReturn là mảng chứa các chương mới, tiếp tục tăng page
		    */
		    
			///story.startPage = story.getlink_page;
			//story.url = story.startPage.replace('%s%', startPage);
			//returnSend = false;
			
			/*
				Dùng ajax để get nội dung chương
				Nếu hoàn thành tiếp tục gọi getAutoChaptersViaPage
			*/	
			//newData1 = $.parseJSON(linksReturn);
			//console.log(newData1);
			$.ajax({
				url: "<?php echo HOME; ?>index.php?module=user&act=ajax&insertChapter=1",
				type: 'POST',
				cache: false,
				async: false,
				timeout: 1800000,
				data: {links: linkParse, storyData: story},
				success: function(insertData){
					$.ajax({
			    		url : "<?php echo BASE_URL; ?>index.php?module=user&act=ajax&"+ajaxSubmit+"=1",
			    		type : 'POST',
			    		cache: false,
			    		async: false,
			    		timeout: 1800000,
			    		data: {story_id:story.id},
			    		success: function(){
							console.log('get first page done auto');
				    	}
					});
					i = 1;
					$.each(linksReturn, function(e,index){
						if(i%2==0){trclass = 'class="odd"';}else{trclass='class="even"';}
						if(index.href == 'Error') {status = '<td class="fail_story">Fail</td>';}else{status = '<td>OK</td>'}
						$('#report_chapter_table').append('<tr '+trclass+'><td>'+i+'</td><td>'+index.link+'</td><td>' + index.title + '</td><td>'+story.startPage+'</td><td>'+index.tap+'</td><td>'+index.chapt+'</td>'+status);
						i++;
					});
				},
			});
			
			//console.log('here if khac false - ' + data1);
			//if(data1) returnData = $.parseJSON(data1);
			story.startPage = parseInt(story.startPage) + 1;
			story.url = story.pattern_url;
			//console.log(story);
			return story;

	    }

	   	function getChaptersViaPage(newData){
		   	console.log(newData);
		   	startPage = newData.startPage;
		   	
	   		newurl = newData.url.replace('%s%', startPage);
	  		
	   		returnSend = false;
	   		storySource = newData.getlink_type;
	   		$.ajax({
				url: "<?php echo HOME; ?>index.php?module=user&act=ajax&validateGetChapter=1",
				type: 'POST',
				cache: false,
				//dataType: 'jsonp',
				async: false,
				timeout: 1800000,
				data: {txtSource: storySource, txtSourceUrl: newurl, truyenId : newData.id},
				success: function(data1){
					
					if(data1 != 'het'){
						newData1 = $.parseJSON(data1);
						//console.log(newData);
							$.ajax({
								url: "<?php echo HOME; ?>index.php?module=user&act=ajax&insertChapter=1",
								type: 'POST',
								cache: false,
								async: false,
								data: {links: data1, storyData: newData},
								success: function(insertData){
									
									i = 1;
									$.each(newData1, function(e,index){
										if(i%2==0){trclass = 'class="odd"';}else{trclass='class="even"';}
										if(index.href == 'Error') {status = '<td class="fail_story">Fail</td>';}else{status = '<td>OK</td>'}
										$('#report_chapter_table').append('<tr '+trclass+'><td>'+i+'</td><td>'+index.link+'</td><td>' + index.title + '</td><td>'+newData.startPage+'</td><td>'+index.tap+'</td><td>'+index.chapt+'</td>'+status);
										i++;
									});
								},

								
							});
						
						//console.log('here if khac false - ' + data1);
						//if(data1) returnData = $.parseJSON(data1);
						
					}else{
						//console.log('here returnSend true');
						console.log('het');
						returnSend = true;
						return false;
					}
					
				},

				error: function(x, t, m) {
					newData.startPage = newData.startPage - 1;
			        if(t==="timeout") {
			            alert("got timeout");
			        } else {
				        console.log(x);
				        console.log(t);
				        console.log(m);
			        }
			    },
				
				complete: function(jqXHR, textStatus){
					
					if(returnSend == true){
						console.log('returnSend ' + returnSend);
						return;
					}

					newData.startPage = newData.startPage + 1;
					getChaptersViaPage(newData);
				}
			});
	   	}
	    
	    $('.select2').select2({ width: '250' });
		$('#txtSource').select2({width: '150'});
	});
</script>

<script src="public/exts/js/jquery.center.js"></script>

<?php 
echo '<pre>';
print_r($_SESSION['chapts']);
echo '</pre>';
?>
